package com.tebiecloud.common.utils;

import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.ScriptResult;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JsoupHttpClientUtils {

    public static Map<String,String> jsoupSignContract(String url){
        Map<String,String> resultMap = new HashMap<String,String>();
        // 创建webclient
        WebClient webClient = new WebClient();
        // 启动JS 支持
        webClient.getOptions().setJavaScriptEnabled(true);
        //忽略ssl认证
        webClient.getOptions().setUseInsecureSSL(true);
        // 取消 CSS 支持
        webClient.getOptions().setCssEnabled(false);
        // 获取指定网页实体
        webClient.getOptions().setThrowExceptionOnScriptError(true);//运行错误时，不抛出异常
        webClient.setAjaxController(new NicelyResynchronizingAjaxController());// 设置Ajax异步
        HtmlPage page = null;
        try {
            page = (HtmlPage) webClient.getPage(url);
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
        webClient.waitForBackgroundJavaScript(10000);
        HtmlElement div = page.getHtmlElementById("signContract");
        DomNodeList<HtmlElement> picnodes=div.getElementsByTagName("span").get(0).getElementsByTagName("button");
        resultMap.put("status","error");
        for(int i=0;i<picnodes.size();i++){
            HtmlElement pic=picnodes.get(i);
            String hrefValue = "signContract()";
            ScriptResult s = new ScriptResult("OK");
            try {
                s = page.executeJavaScript(hrefValue);//执行js方法
            }catch (Exception e){
                System.out.println(e.getMessage());
            }
            if(s!=null){
                resultMap.put("status","OK");
            }
        }
        return resultMap;
    }

    public static void main(String[] args){
        JsoupHttpClientUtils.jsoupSignContract("http://116.228.64.55:6900/yungateway/member/signContract.html?sysid=1902271423530473681&v=2.0&timestamp=2019-09-17+13%3A09%3A24&sign=P8WO2%2FvkzqSjk60K8SgJAwzlYVGDtBbQCrJmhJ3QRKHoFCTdDzWRuktZCHP2vL2Zrrccpweh4ry5yOFh%2Fs1kaAYh%2FfA48gikQgBLMYgrLacdAc%2Bwsbzz4IaB%2Frb6b%2Bfm3l3joyp9NMMqXR%2FzPohPR8v0KSYpbYoo56npEwGsAvc%3D&req=%7B%22method%22%3A%22signContract%22%2C%22param%22%3A%7B%22bizUserId%22%3A%221EE15701C0A80C321BC7FDDF79D408DF%22%2C%22memberType%22%3A%223%22%2C%22jumpUrl%22%3A%22http%3A%2F%2F112.74.179.177%3A43004%2F%22%2C%22backUrl%22%3A%22http%3A%2F%2F112.74.179.177%3A43004%2F%22%2C%22source%22%3A%222%22%7D%2C%22service%22%3A%22MemberService%22%7D&");
    }
}
